package interceptor

import (
	"context"
	"errors"
	"github.com/go-kratos/kratos/v2/metadata"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/http"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gotham-plan-manage/pkg/jwt_util"
)

/*
   @author:zhongyang
   @date:2023/5/31
   @description:鉴权拦截器
*/

func Auth() middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			if md, ok := metadata.FromServerContext(ctx); ok {
				// 先从grpc取数据
				token := md.Get("x-md-global-token")
				if token == "" {
					// 再从http头取数据
					if ts, ok := transport.FromServerContext(ctx); ok {
						if ht, ok := ts.(http.Transporter); ok {
							token = ht.Request().Header.Get("token")
						}
					}
				}
				claims, err := jwt_util.ParseToken(token)
				if err != nil {
					return nil, status.Error(codes.PermissionDenied, errors.New("无权访问").Error())
				}
				ctx = context.WithValue(ctx, "user_id", claims.UserId)
				ctx = context.WithValue(ctx, "account", claims.Account)
				return handler(ctx, req)
			}
			return nil, status.Error(codes.PermissionDenied, errors.New("无权访问").Error())
		}
	}
}
